<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import type { FormInstance, TableColumnsType } from 'ant-design-vue';

// 定义接口类型
interface CurrencyPair {
  id?: number;
  code: string;
  name: string;
  baseCurrency: string;
  quoteCurrency: string;
  description?: string;
  status: string;
  createTime?: string;
  updateTime?: string;
}

// 响应式数据
const loading = ref(false);
const modalVisible = ref(false);
const modalLoading = ref(false);
const modalTitle = ref('新增货币对');
const isEdit = ref(false);
const editId = ref<number>();

const formRef = ref<FormInstance>();
const dataSource = ref<CurrencyPair[]>([]);

const searchForm = reactive({
  keyword: ''
});

const formData = reactive({
  code: '',
  name: '',
  baseCurrency: '',
  quoteCurrency: '',
  description: '',
  status: '1'
});

// 重置表单函数
const resetForm = () => {
  formData.code = '';
  formData.name = '';
  formData.baseCurrency = '';
  formData.quoteCurrency = '';
  formData.description = '';
  formData.status = '1';
  formRef.value?.resetFields();
};

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
});

// 表格列定义
const columns: TableColumnsType = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    customRender: ({ index }) => index + 1 + (pagination.current - 1) * pagination.pageSize
  },
  {
    title: '货币对代码',
    dataIndex: 'code',
    key: 'code',
    width: 120
  },
  {
    title: '货币对名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '基础货币',
    dataIndex: 'baseCurrency',
    key: 'baseCurrency',
    width: 100
  },
  {
    title: '计价货币',
    dataIndex: 'quoteCurrency',
    key: 'quoteCurrency',
    width: 100
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right'
  }
];

// 表单验证规则
const formRules = {
  code: [
    { required: true, message: '请输入货币对代码', trigger: 'blur' as const },
    { pattern: /^[A-Z]{6}$/, message: '货币对代码格式不正确，应为6位大写字母', trigger: 'blur' as const }
  ],
  name: [{ required: true, message: '请输入货币对名称', trigger: 'blur' as const }],
  baseCurrency: [
    { required: true, message: '请输入基础货币', trigger: 'blur' as const },
    { pattern: /^[A-Z]{3}$/, message: '基础货币代码格式不正确，应为3位大写字母', trigger: 'blur' as const }
  ],
  quoteCurrency: [
    { required: true, message: '请输入计价货币', trigger: 'blur' as const },
    { pattern: /^[A-Z]{3}$/, message: '计价货币代码格式不正确，应为3位大写字母', trigger: 'blur' as const }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' as const }]
};

// 方法定义
const loadData = async () => {
  loading.value = true;
  try {
    // 模拟API调用
    await new Promise<void>(resolve => {
      setTimeout(() => {
        resolve();
      }, 500);
    });

    // 模拟数据
    const mockData: CurrencyPair[] = [
      {
        id: 1,
        code: 'USDCNY',
        name: '美元/人民币',
        baseCurrency: 'USD',
        quoteCurrency: 'CNY',
        description: '美元对人民币汇率',
        status: '1',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        code: 'EURUSD',
        name: '欧元/美元',
        baseCurrency: 'EUR',
        quoteCurrency: 'USD',
        description: '欧元对美元汇率',
        status: '1',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00'
      }
    ];

    dataSource.value = mockData;
    pagination.total = mockData.length;
  } catch {
    window.$message?.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

const handleReset = () => {
  searchForm.keyword = '';
  pagination.current = 1;
  loadData();
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

const handleAdd = () => {
  modalTitle.value = '新增货币对';
  isEdit.value = false;
  resetForm();
  modalVisible.value = true;
};

const handleEdit = (record: any) => {
  const currencyPair = record as CurrencyPair;
  modalTitle.value = '编辑货币对';
  isEdit.value = true;
  editId.value = currencyPair.id;
  formData.code = currencyPair.code;
  formData.name = currencyPair.name;
  formData.baseCurrency = currencyPair.baseCurrency;
  formData.quoteCurrency = currencyPair.quoteCurrency;
  formData.description = currencyPair.description || '';
  formData.status = currencyPair.status;
  modalVisible.value = true;
};

const handleDelete = (record: any) => {
  const currencyPair = record as CurrencyPair;
  // 这里应该调用删除API
  console.log('删除货币对:', currencyPair);
  window.$message?.success('删除成功');
  loadData();
};

const handleModalOk = async () => {
  try {
    await formRef.value?.validate();
    modalLoading.value = true;

    // 模拟API调用
    await new Promise<void>(resolve => {
      setTimeout(() => {
        resolve();
      }, 1000);
    });

    window.$message?.success(isEdit.value ? '编辑成功' : '新增成功');
    modalVisible.value = false;
    loadData();
  } catch {
    // 表单验证失败
  } finally {
    modalLoading.value = false;
  }
};

const handleModalCancel = () => {
  modalVisible.value = false;
  resetForm();
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<template>
  <div>
    <ACard title="货币对管理" :bordered="false">
      <template #extra>
        <ASpace>
          <AButton type="primary" @click="handleAdd">
            <template #icon>
              <icon-carbon:add />
            </template>
            新增货币对
          </AButton>
        </ASpace>
      </template>

      <div class="mb-4">
        <ASpace>
          <AInput
            v-model:value="searchForm.keyword"
            placeholder="请输入货币对代码或名称搜索"
            allow-clear
            @press-enter="handleSearch"
          />
          <AButton type="primary" @click="handleSearch">
            <template #icon>
              <icon-carbon:search />
            </template>
            搜索
          </AButton>
          <AButton @click="handleReset">
            <template #icon>
              <icon-carbon:reset />
            </template>
            重置
          </AButton>
        </ASpace>
      </div>

      <ATable
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <ATag :color="record.status === '1' ? 'green' : 'red'">
              {{ record.status === '1' ? '启用' : '禁用' }}
            </ATag>
          </template>
          <template v-else-if="column.key === 'action'">
            <ASpace>
              <AButton type="link" size="small" @click="handleEdit(record)">编辑</AButton>
              <AButton type="link" size="small" danger @click="handleDelete(record)">删除</AButton>
            </ASpace>
          </template>
        </template>
      </ATable>
    </ACard>

    <!-- 新增/编辑货币对模态框 -->
    <AModal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <AForm ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <AFormItem label="货币对代码" name="code">
          <AInput v-model:value="formData.code" placeholder="请输入货币对代码，如USDCNY" />
        </AFormItem>
        <AFormItem label="货币对名称" name="name">
          <AInput v-model:value="formData.name" placeholder="请输入货币对名称" />
        </AFormItem>
        <AFormItem label="基础货币" name="baseCurrency">
          <AInput v-model:value="formData.baseCurrency" placeholder="请输入基础货币代码，如USD" />
        </AFormItem>
        <AFormItem label="计价货币" name="quoteCurrency">
          <AInput v-model:value="formData.quoteCurrency" placeholder="请输入计价货币代码，如CNY" />
        </AFormItem>
        <AFormItem label="描述" name="description">
          <ATextarea v-model:value="formData.description" placeholder="请输入描述" :rows="3" />
        </AFormItem>
        <AFormItem label="状态" name="status">
          <ARadioGroup v-model:value="formData.status">
            <ARadio value="1">启用</ARadio>
            <ARadio value="0">禁用</ARadio>
          </ARadioGroup>
        </AFormItem>
      </AForm>
    </AModal>
  </div>
</template>

<style scoped>
/* 可以添加自定义样式 */
</style>
